<template>
  <div class="app-container mobile-config-page">
    <el-card class="filter-card" shadow="never">
      <el-form :model="queryParams" label-width="60px" inline class="filter-form">
        <el-form-item label="水厂">
          <el-select
            v-model="queryParams.waterPlantId"
            placeholder="请选择水厂"
            clearable
            filterable
            style="width: 240px"
            :loading="factoryLoading"
          >
            <el-option
              v-for="item in factoryOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :loading="tableLoading">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="action-btns">
        <el-button type="primary" @click="openDialog('add')">新增配置</el-button>
        <el-button type="danger" plain @click="handleDelete()" :disabled="!selectedIds.length">
          批量删除
        </el-button>
      </div>
    </el-card>

    <el-card shadow="never">
      <el-table
        border
        :data="displayList"
        v-loading="tableLoading"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
      >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column prop="waterPlantName" label="水厂" width="160" show-overflow-tooltip />
        <el-table-column prop="configurationType" label="组态类型" width="140" show-overflow-tooltip />
        <el-table-column prop="componentName" label="组件名称" width="140" show-overflow-tooltip />
        <el-table-column prop="componentPosition" label="组件位置" width="140" show-overflow-tooltip />
        <el-table-column prop="componentSize" label="组件大小" width="140" show-overflow-tooltip />
        <el-table-column prop="dataSource" label="数据源" min-width="160" show-overflow-tooltip />
        <el-table-column prop="dataMapping" label="数据映射" min-width="180" show-overflow-tooltip />
        <el-table-column prop="sortOrder" label="排序" width="80" />
        <el-table-column prop="isDisplayed" label="是否展示" width="120">
          <template #default="{ row }">
            <el-tag :type="row.isDisplayed === 1 ? 'success' : 'info'">
              {{ row.isDisplayed === 1 ? '展示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastUpdateTime" label="更新时间" width="180" show-overflow-tooltip />
        <el-table-column prop="remark" label="备注" min-width="140" show-overflow-tooltip />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="table-ops">
              <el-button size="small" @click="openDetail(row)">详情</el-button>
              <el-button size="small" type="primary" @click="openDialog('edit', row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="640px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        v-loading="formLoading"
      >
        <el-form-item label="水厂" prop="waterPlantId">
          <el-select v-model="formData.waterPlantId" placeholder="请选择水厂" filterable>
            <el-option
              v-for="item in factoryOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="组态类型" prop="configurationType">
          <el-input v-model="formData.configurationType" placeholder="如：首页、数据详情页" maxlength="50" />
        </el-form-item>
        <el-form-item label="组件 ID" prop="componentId">
          <el-input
            v-model="formData.componentId"
            placeholder="请输入组件ID"
            type="number"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="组件名称" prop="componentName">
          <el-input v-model="formData.componentName" placeholder="请输入组件名称" maxlength="100" />
        </el-form-item>
        <el-form-item label="组件位置" prop="componentPosition">
          <el-input v-model="formData.componentPosition" placeholder="请输入组件位置" maxlength="100" />
        </el-form-item>
        <el-form-item label="组件大小" prop="componentSize">
          <el-input v-model="formData.componentSize" placeholder="示例：375x200" maxlength="50" />
        </el-form-item>
        <el-form-item label="数据源" prop="dataSource">
          <el-input v-model="formData.dataSource" placeholder="请输入数据源" maxlength="200" />
        </el-form-item>
        <el-form-item label="数据映射" prop="dataMapping">
          <el-input
            v-model="formData.dataMapping"
            type="textarea"
            :rows="2"
            placeholder="字段映射描述"
            maxlength="500"
          />
        </el-form-item>
        <el-form-item label="是否展示" prop="isDisplayed">
          <el-switch v-model="formData.isDisplayed" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="排序顺序" prop="sortOrder">
          <el-input-number v-model="formData.sortOrder" :min="0" :max="9999" :controls="false" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="formLoading">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="detailVisible"
      title="配置详情"
      width="520px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-scrollbar class="detail-scroll" v-loading="detailLoading">
        <el-descriptions v-if="detailData" :column="1" border>
          <el-descriptions-item label="水厂">{{ getWaterPlantName(detailData.waterPlantId) }}</el-descriptions-item>
          <el-descriptions-item label="组态类型">{{ detailData.configurationType || '-' }}</el-descriptions-item>
          <el-descriptions-item label="组件ID">{{ detailData.componentId ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="组件名称">{{ detailData.componentName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="组件位置">{{ detailData.componentPosition || '-' }}</el-descriptions-item>
          <el-descriptions-item label="组件大小">{{ detailData.componentSize || '-' }}</el-descriptions-item>
          <el-descriptions-item label="数据源">{{ detailData.dataSource || '-' }}</el-descriptions-item>
          <el-descriptions-item label="数据映射">{{ detailData.dataMapping || '-' }}</el-descriptions-item>
          <el-descriptions-item label="是否展示">
            {{ detailData.isDisplayed === 1 ? '展示' : '隐藏' }}
          </el-descriptions-item>
          <el-descriptions-item label="排序">{{ detailData.sortOrder ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ detailData.lastUpdateTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ detailData.remark || '-' }}</el-descriptions-item>
        </el-descriptions>
        <el-empty v-else description="暂无数据" />
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getFactoryList,
  listMobileConfig,
  getMobileConfig,
  addMobileConfig,
  updateMobileConfig,
  deleteMobileConfig
} from '@/api/prod_operate/sys_setting/mobile'

const factoryOptions = ref([])
const configList = ref([])
const total = ref(0)

const factoryLoading = ref(false)
const tableLoading = ref(false)
const formLoading = ref(false)
const detailLoading = ref(false)

const dialogVisible = ref(false)
const detailVisible = ref(false)
const dialogMode = ref('add')

const selectedIds = ref([])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  waterPlantId: undefined
})

const formRef = ref(null)
const formData = reactive(getDefaultForm())
const detailData = ref(null)

const rules = {
  waterPlantId: [{ required: true, message: '请选择水厂', trigger: 'change' }],
  configurationType: [{ required: true, message: '请输入组态类型', trigger: 'blur' }],
  componentName: [{ required: true, message: '请输入组件名称', trigger: 'blur' }],
  componentId: [{ required: true, message: '请输入组件ID', trigger: 'blur' }]
}

const dialogTitle = computed(() =>
  dialogMode.value === 'add' ? '新增移动端配置' : '编辑移动端配置'
)

const displayList = computed(() =>
  configList.value.map(item => ({
    ...item,
    waterPlantName: getWaterPlantName(item.waterPlantId)
  }))
)

function getDefaultForm() {
  return {
    mobileConfigId: undefined,
    waterPlantId: '',
    configurationType: '',
    componentId: '',
    componentName: '',
    componentPosition: '',
    componentSize: '',
    dataSource: '',
    dataMapping: '',
    isDisplayed: 1,
    sortOrder: 0,
    remark: ''
  }
}

const getWaterPlantName = id => {
  const target = factoryOptions.value.find(item => String(item.dictValue) === String(id))
  return target?.dictLabel || '--'
}

const fetchFactoryOptions = async () => {
  try {
    factoryLoading.value = true
    const res = await getFactoryList()
    factoryOptions.value = res.data || []
  } catch (error) {
    console.error(error)
    ElMessage.error('获取水厂列表失败')
  } finally {
    factoryLoading.value = false
  }
}

const fetchList = async () => {
  try {
    tableLoading.value = true
    const params = {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize
    }
    if (queryParams.waterPlantId !== undefined && queryParams.waterPlantId !== null && queryParams.waterPlantId !== '') {
      params.waterPlantId = Number(queryParams.waterPlantId)
    }
    const res = await listMobileConfig(params)
    configList.value = res.rows || []
    total.value = res.total || 0
    selectedIds.value = []
  } catch (error) {
    console.error(error)
    ElMessage.error('获取移动端配置列表失败')
  } finally {
    tableLoading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNum = 1
  fetchList()
}

const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.pageSize = 10
  queryParams.waterPlantId = undefined
  fetchList()
}

const handleSizeChange = size => {
  queryParams.pageSize = size
  queryParams.pageNum = 1
  fetchList()
}

const handleCurrentChange = page => {
  queryParams.pageNum = page
  fetchList()
}

const handleSelectionChange = selection => {
  selectedIds.value = selection.map(item => item.mobileConfigId)
}

const openDialog = async (mode, row) => {
  dialogMode.value = mode
  dialogVisible.value = true
  await nextTick()
  formRef.value?.clearValidate()

  if (mode === 'edit' && row) {
    formLoading.value = true
    try {
      const data = await fetchDetail(row.mobileConfigId)
      assignForm(data)
    } catch (error) {
      console.error(error)
      ElMessage.error('获取配置详情失败')
    } finally {
      formLoading.value = false
    }
  } else {
    assignForm(getDefaultForm())
  }
}

const assignForm = data => {
  Object.assign(formData, getDefaultForm(), {
    ...data,
    waterPlantId:
      data.waterPlantId !== undefined && data.waterPlantId !== null
        ? String(data.waterPlantId)
        : '',
    componentId: data.componentId !== undefined && data.componentId !== null ? String(data.componentId) : '',
    sortOrder: data.sortOrder ?? 0,
    isDisplayed: data.isDisplayed ?? 1
  })
}

const submitForm = async () => {
  if (!formRef.value) return
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    formLoading.value = true
    const payload = buildPayload(formData)
    if (dialogMode.value === 'add') {
      await addMobileConfig(payload)
      ElMessage.success('新增成功')
    } else {
      await updateMobileConfig(payload)
      ElMessage.success('修改成功')
    }
    dialogVisible.value = false
    fetchList()
  } catch (error) {
    if (error === false) {
      return
    }
    console.error(error)
    const msg = error?.response?.data?.msg || error?.message || '操作失败'
    ElMessage.error(msg)
  } finally {
    formLoading.value = false
  }
}

const buildPayload = data => {
  const payload = { ...data }
  payload.waterPlantId =
    payload.waterPlantId !== '' && payload.waterPlantId !== undefined
      ? Number(payload.waterPlantId)
      : undefined
  payload.componentId =
    payload.componentId !== '' && payload.componentId !== undefined && payload.componentId !== null
      ? Number(payload.componentId)
      : undefined
  payload.sortOrder =
    payload.sortOrder !== '' && payload.sortOrder !== undefined && payload.sortOrder !== null
      ? Number(payload.sortOrder)
      : 0
  payload.isDisplayed = Number(payload.isDisplayed)
  return payload
}

const handleDelete = async row => {
  const ids = row ? [row.mobileConfigId] : selectedIds.value
  if (!ids.length) {
    ElMessage.warning('请选择要删除的配置')
    return
  }
  try {
    await ElMessageBox.confirm('确定删除选中的配置吗？', '提示', {
      type: 'warning'
    })
    await deleteMobileConfig(ids.join(','))
    ElMessage.success('删除成功')
    fetchList()
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      return
    }
    console.error(error)
    ElMessage.error(error?.response?.data?.msg || '删除失败')
  }
}

const openDetail = async row => {
  detailVisible.value = true
  detailLoading.value = true
  try {
    detailData.value = await fetchDetail(row.mobileConfigId)
  } catch (error) {
    console.error(error)
    ElMessage.error('获取详情失败')
  } finally {
    detailLoading.value = false
  }
}

const fetchDetail = async mobileConfigId => {
  const res = await getMobileConfig(mobileConfigId)
  return res.data || {}
}

onMounted(async () => {
  await fetchFactoryOptions()
  fetchList()
})
</script>

<style scoped>
.mobile-config-page .filter-card {
  margin-bottom: 16px;
}

.filter-form {
  margin-bottom: 12px;
}

.action-btns {
  display: flex;
  gap: 12px;
}

.table-ops {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.pagination-wrapper {
  margin-top: 16px;
  text-align: right;
}

.detail-scroll {
  padding-right: 8px;
  max-height: calc(100vh - 200px);
}
</style>

